/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: $
 * --------------------------------------------------------------------------
 */


package org.osami.commons.encryption.internal.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * A {@code IOUtils} is ...
 *
 * @author Guillaume Sauthier
 */
public class IOUtils {
    private static final int BUFFER_SIZE = 1024;

    /**
     * Private empty constructor for utility class.
     */
    private IOUtils() {}

    /**
     * Loads the content of the file as a byte array
     * @param file
     * @return
     * @throws java.io.IOException
     */
    public static byte[] getBytesFromFile(final File file) throws IOException {

        // Prepare the streams
        FileInputStream fis = new FileInputStream(file);

        try {
            return getBytesFromInputStream(fis);
        } finally {
            fis.close();
        }
    }

    public static byte[] getBytesFromUrl(URL resource) throws IOException {

        // Fail fast check
        if (resource == null) {
            throw new IOException("URL is null");
        }

        InputStream is = resource.openStream();

        try {
            return getBytesFromInputStream(is);
        } finally {
            is.close();
        }

    }

    public static byte[] getBytesFromInputStream(final InputStream is) throws IOException{
        // Prepare the streams
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // Init a temporary buffer
        byte[] buffer = new byte[BUFFER_SIZE];

        // Read the file's content into the BOS
        int read = 0;
        while((read = is.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }

        // return back the bytes array
        return bos.toByteArray();
    }
}
